<template>
	<view class="score-detail-page">
		<view class="score-summary">
			<view class="score-left">
				<text class="score-label">当前积分</text>
				<text class="score-value">{{ totalScore }}</text>
				<text class="score-rule-link" @click="showScoreRule">积分规则</text>
			</view>
			<button class="exchange-btn" @click="goToExchange">积分兑换</button>
		</view>
		<view class="tab-bar">
			<view
				v-for="tab in tabs"
				:key="tab.type"
				:class="['tab-item', {active: currentType === tab.type}]"
				@click="switchTab(tab.type)"
			>
				{{ tab.text }}
			</view>
		</view>
		<view class="score-list">
			<view v-for="item in filteredList" :key="item.id" class="score-item">
				<uni-icons :type="item.icon" size="20" :color="item.amount > 0 ? '#4CAF50' : '#FF5252'" />
				<view class="score-info">
					<text class="score-desc">{{ item.desc }}</text>
					<text class="score-time">{{ item.time }}</text>
				</view>
				<text :class="['score-amount', item.amount > 0 ? 'plus' : 'minus']">
					{{ item.amount > 0 ? '+' : '' }}{{ item.amount }}
				</text>
			</view>
			<view v-if="filteredList.length === 0" class="empty-tip">暂无明细</view>
		</view>
		
		<!-- 积分规则弹窗 -->
		<uni-popup ref="scoreRulePopup" type="center" :mask="true">
			<view class="score-rule-popup">
				<view class="popup-header">
					<text class="popup-title">积分规则说明</text>
					<uni-icons type="close" size="20" color="#999" @click="closeScoreRule" />
				</view>
				
				<scroll-view class="rule-scroll" scroll-y>
					<view class="rule-item">
						<text class="rule-title">一、积分获取方式</text>
						<view class="rule-content">
							<view class="rule-detail">
								<text class="rule-type">每日签到</text>
								<text class="rule-desc">每日首次签到可获得5积分，连续签到7天额外奖励20积分</text>
							</view>
							<view class="rule-detail">
								<text class="rule-type">发布帖子</text>
								<text class="rule-desc">发布符合规范的帖子可获得10积分/篇，优质帖子（管理员推荐）额外奖励50积分</text>
							</view>
							<view class="rule-detail">
								<text class="rule-type">帖子/评论获赞</text>
								<text class="rule-desc">帖子每获10个赞可获得2积分，评论每获5个赞可获得1积分（每日上限50积分）</text>
							</view>
							<view class="rule-detail">
								<text class="rule-type">完成任务</text>
								<text class="rule-desc">完成平台指定任务（如新手任务、日常任务）可获得10-100积分/次，具体以任务说明为准</text>
							</view>
						</view>
					</view>
					
					<view class="rule-item">
						<text class="rule-title">二、积分扣除方式</text>
						<view class="rule-content">
							<view class="rule-detail">
								<text class="rule-type">帖子置顶</text>
								<text class="rule-desc">申请帖子置顶需扣除50积分/天，取消置顶不返还积分</text>
							</view>
							<view class="rule-detail">
								<text class="rule-type">违规处罚</text>
								<text class="rule-desc">发布违规内容（如广告、辱骂、谣言）将扣除100-500积分/次，情节严重者清零积分并封号</text>
							</view>
							<view class="rule-detail">
								<text class="rule-type">积分兑换</text>
								<text class="rule-desc">兑换平台商品或服务时，将按兑换规则扣除对应积分</text>
							</view>
						</view>
					</view>
					
					<view class="rule-item">
						<text class="rule-title">三、积分有效期与说明</text>
						<view class="rule-content">
							<view class="rule-detail">
								<text class="rule-desc">1. 积分自获取之日起有效期为1年，过期未使用将自动清零（可在"积分明细"中查看过期时间）</text>
							</view>
							<view class="rule-detail">
								<text class="rule-desc">2. 积分仅可在本平台使用，不兑现、不找零、不转让</text>
							</view>
							<view class="rule-detail">
								<text class="rule-desc">3. 若对积分变动有疑问，可联系客服（入口：我的 → 设置 → 客服反馈）</text>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				totalScore: 0,
				tabs: [
					{ text: '获取明细', type: 'gain' },
					{ text: '扣除明细', type: 'cost' }
				],
				currentType: 'gain',
				scoreList: [],
				scoreRulePopup: null
			};
		},
		onReady(){
			this.scoreRulePopup = this.$refs.scoreRulePopup
		},
		computed: {
			filteredList() {
				return this.scoreList.filter(item => item.type === this.currentType)
			}
		},
		methods: {
			showScoreRule() {
				this.scoreRulePopup.open();
			},
			
			closeScoreRule() {
				this.scoreRulePopup.close();
			},
			
			// 获取积分记录 - 使用云函数
			async getScoreRecords() {
				try {
					const userInfo = uni.getStorageSync('uni-id-pages-userInfo')
					if (!userInfo || !userInfo._id) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						})
						return
					}
					
					// 调用积分管理云函数
					const res = await uniCloud.callFunction({
						name: 'scoreManager',
						data: {
							action: 'get_records',
							userId: userInfo._id
						}
					})
					
					console.log('云函数返回结果:', res)
					
					if (res.result.code === 200) {
						const data = res.result.data
						
						// 处理积分记录
						this.scoreList = data.records.map(record => {
							const isGain = record.score > 0
							return {
								id: record._id,
								type: isGain ? 'gain' : 'cost',
								icon: this.getIconByType(record.type),
								desc: record.description || this.getDescriptionByType(record.type),
								time: this.formatTime(record.create_time),
								amount: record.score
							}
						})
						
						// 设置总积分
						this.totalScore = data.totalScore || 0
						
						console.log('积分记录:', this.scoreList)
						console.log('总积分:', this.totalScore)
					} else {
						console.error('云函数返回错误:', res.result)
						uni.showToast({
							title: res.result.msg || '获取积分记录失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('获取积分记录失败：', error)
					uni.showToast({
						title: '获取积分记录失败',
						icon: 'none'
					})
				}
			},
			
			getIconByType(type) {
				const iconMap = {
					'daily_sign': 'calendar',
					'post_create': 'plus',
					'post_like': 'heart',
					'comment_like': 'chat',
					'task_complete': 'checkmark',
					'task_evaluation_reward': 'star', // 新增：评价奖励图标
					'post_pin': 'pushpin',
					'violation': 'close',
					'exchange': 'wallet'
				}
				return iconMap[type] || 'info'
			},
			
			getDescriptionByType(type) {
				const descMap = {
					'daily_sign': '每日签到',
					'post_create': '发布帖子',
					'post_like': '帖子获赞',
					'comment_like': '评论获赞',
					'task_complete': '完成任务',
					'task_evaluation_reward': '任务评价奖励', // 新增：评价奖励描述
					'post_pin': '帖子置顶',
					'violation': '违规处罚',
					'exchange': '积分兑换'
				}
				return descMap[type] || '积分变动'
			},
			
			formatTime(timestamp) {
				// 处理时间戳格式（数字）和日期格式
				let date;
				if (typeof timestamp === 'number') {
					date = new Date(timestamp);
				} else {
					date = new Date(timestamp);
				}
				
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				const hour = String(date.getHours()).padStart(2, '0')
				const minute = String(date.getMinutes()).padStart(2, '0')
				return `${year}-${month}-${day} ${hour}:${minute}`
			},
			
			switchTab(type) {
				this.currentType = type
			},
			
			goToExchange() {
				uni.showToast({ title: '跳转到兑换页面', icon: 'none' })
			}
		},
		
		onLoad() {
			this.getScoreRecords()
		},
		
		onShow() {
			this.getScoreRecords()
		}
	}
</script>

<style lang="scss">
	.score-detail-page {
		background: #f5f6fa;
		min-height: 100vh;
		padding-bottom: 40rpx;
	}
	.score-summary {
		background: #fff;
		border-radius: 18rpx;
		box-shadow: 0 4px 16px rgba(64,128,255,0.10);
		margin: 0rpx 24rpx 0 24rpx;
		padding: 32rpx 24rpx 24rpx 24rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: relative;
	}
	.score-left {
		display: flex;
		flex-direction: column;
	}
	.score-label {
		font-size: 15px;
		color: #888;
	}
	.score-value {
		font-size: 32px;
		font-weight: 700;
		color: #4080FF;
		margin: 0 16rpx;
	}
	.score-rule-link {
		font-size: 12px;
		color: #4080FF;
		margin-top: 8rpx;
		cursor: pointer;
		text-decoration: underline;
	}
	.exchange-btn {
		font-size: 14px;
		color: #fff;
		background: linear-gradient(90deg, #4080FF, #60A9FF);
		border-radius: 24rpx;
		padding: 10rpx 28rpx;
		border: none;
	}
	.tab-bar {
		display: flex;
		background: #fff;
		border-radius: 16rpx;
		margin: 0rpx 24rpx 0 24rpx;
		box-shadow: 0 2px 8px rgba(0,0,0,0.04);
		overflow: hidden;
	}
	.tab-item {
		flex: 1;
		text-align: center;
		padding: 28rpx 0;
		font-size: 17px;
		color: #888;
		cursor: pointer;
		transition: color 0.2s;
		letter-spacing: 1px;
	}
	.tab-item.active {
		color: #4080FF;
		font-weight: 700;
		background: linear-gradient(to right, #eaf2ff, #f5faff);
		box-shadow: 0 2px 8px rgba(64,128,255,0.06);
	}
	.score-list {
		margin: 36rpx 24rpx 0 24rpx;
	}
	.score-item {
		background: #fff;
		border-radius: 16rpx;
		box-shadow: 0 2px 8px rgba(64,128,255,0.08);
		padding: 22rpx 20rpx 18rpx 20rpx;
		margin-bottom: 18rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	.score-info {
		flex: 1;
		margin-left: 16rpx;
	}
	.score-desc {
		font-size: 15px;
		color: #222;
		font-weight: 600;
	}
	.score-time {
		font-size: 12px;
		color: #aaa;
		margin-top: 4rpx;
		display: block;
	}
	.score-amount {
		font-size: 18px;
		font-weight: 700;
		min-width: 60rpx;
		text-align: right;
	}
	.score-amount.plus {
		color: #4CAF50;
	}
	.score-amount.minus {
		color: #FF5252;
	}
	.empty-tip {
		text-align: center;
		color: #bbb;
		margin-top: 80rpx;
		font-size: 17px;
		letter-spacing: 1px;
	}
	
	/* 积分规则弹窗样式 */
	.score-rule-popup {
		width: 85%;
		max-width: 500px;
		background: #fff;
		border-radius: 20rpx;
		padding: 30rpx 20rpx;
		box-sizing: border-box;
	}
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
		padding-bottom: 16rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}
	.popup-title {
		font-size: 18px;
		font-weight: 700;
		color: #333;
	}
	.rule-scroll {
		max-height: 500rpx;
		padding-right: 10rpx;
	}
	.rule-item {
		margin-bottom: 30rpx;
	}
	.rule-title {
		font-size: 16px;
		font-weight: 600;
		color: #4080FF;
		margin-bottom: 16rpx;
		display: block;
	}
	.rule-content {
		padding-left: 10rpx;
	}
	.rule-detail {
		display: flex;
		margin-bottom: 14rpx;
		align-items: flex-start;
	}
	.rule-type {
		font-size: 14px;
		font-weight: 600;
		color: #333;
		min-width: 120rpx;
	}
	.rule-desc {
		font-size: 14px;
		color: #666;
		line-height: 1.6;
		flex: 1;
	}
</style>
